﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Doan.Website.Models;
using Ext.Net;
using Ext.Net.MVC;
using System.Linq.Dynamic;

namespace Doan.Website.Controllers
{
    [DirectController]
    public class QuestionController : Controller
    {
        //Question
        private static DoAnWebsiteEntities db = new DoAnWebsiteEntities();

        [DirectMethod]
        public ActionResult DeleteQuestion(int id)
        {
            var deleteItemA = db.Answers.SingleOrDefault(x => x.AskId == id);
            db.Answers.DeleteObject(deleteItemA);
            db.SaveChanges();
            var deleteItemQ = db.Asks.SingleOrDefault(x => x.AskId == id);
            db.Asks.DeleteObject(deleteItemQ);
            db.SaveChanges();
            var store = X.GetCmp<Store>("QuestionStore");
            store.Reload();
            return this.FormPanel();
        }


        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult ListQuestion()
        {
            Session["includeInActiveQuestion"] = false;
            Session["CharFilterQuestion"] = "";
            return View();
        }

        public ActionResult IncludeInActive()
        {
            var store = X.GetCmp<Store>("QuestionStore");

            Session["includeInActiveQuestion"] = !(bool)Session["includeInActiveQuestion"];

            store.Reload();
            return this.Direct();
        }

        [DirectMethod]
        public ActionResult CharFilterQuestion(string filterstring)
        {
            var store = X.GetCmp<Store>("QuestionStore");
            Session["CharFilterQuestion"] = filterstring;
            store.Reload();
            return this.Direct();
        }

        public ActionResult BindingQuestionStore(StoreRequestParameters parameters)
        {
            var sampleData = (db.Asks.Join(db.GroupNews, tab1 => tab1.GroupNewsId, tab2 => tab2.GroupNewsId,
                                           (tab1, tab2) => new
                                           {
                                               tab1.AskId,
                                               tab1.Content,
                                               tab1.CreateDate,
                                               tab1.Title,
                                               tab2.GNName,
                                               tab1.AuthorName,
                                               tab1.Email,
                                               tab1.Active
                                           })
                             );


            bool includeInActive = (bool)Session["includeInActiveQuestion"];
            string charFilter = (string)Session["CharFilterQuestion"];

            var result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active)));
            if ("0".Equals(charFilter))
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) &&
                    (ent.Title.StartsWith("0") || ent.Title.StartsWith("1") ||
                    ent.Title.StartsWith("2") || ent.Title.StartsWith("3") ||
                    ent.Title.StartsWith("4") || ent.Title.StartsWith("5") ||
                    ent.Title.StartsWith("6") || ent.Title.StartsWith("7") ||
                    ent.Title.StartsWith("8") || ent.Title.StartsWith("9")
                    )));
            }

            else
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) && ent.Title.StartsWith(charFilter)));

            }

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.AskId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData.Select(ent => new { ent.AskId, ent.Content, ent.CreateDate, ent.Title, ent.GNName, ent.AuthorName, ent.Email, ent.Active }), result.Count());
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult CreateQuestion()
        {
            ViewBag.HideTextBox = false;
            ViewBag.GQuestionId = new List<ListItem>();
            ViewBag.GQuestionId = db.GroupNews.ToList().Select(ent => new ListItem { Text = ent.GNName, Value = ent.GroupNewsId.ToString() });

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateQuestion(Ask model)
        {
            if (ModelState.IsValid)
            {
                model.Active = true;
                db.AddToAsks(model);
                db.SaveChanges();

                var answer = new Answer();
                answer.AskId = model.AskId;
                answer.Content = "<b>" + model.Content + "</b" + "\n Chưa có câu trả lời cho câu hỏi này...";
                answer.Active = true;
                answer.CreateDate = DateTime.Now;
                db.AddToAnswers(answer);
                db.SaveChanges();

                X.Msg.Notify("Thành công", "Tạo mới thành công!").Show();
                return this.FormPanel();
            }

            X.Msg.Notify("Lỗi", "Tạo mới không thành công!").Show();

            return this.FormPanel();
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult EditQuestion(int id)
        {
            ViewBag.HideTextBox = false;
            ViewBag.GQuestionId = new List<ListItem>();
            ViewBag.GQuestionId = db.GroupNews.ToList().Select(ent => new ListItem { Text = ent.GNName, Value = ent.GroupNewsId.ToString() });
            Ask Question = db.Asks.Single(m => m.AskId == id);

            return View(Question);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditQuestion(Ask model)
        {
            Ask question1 = db.Asks.Single(c => c.AskId == model.AskId);
            if (ModelState.IsValid)
            {
                db.Asks.Detach(question1);
                db.Asks.Attach(model);
                db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Thành công", "Sửa thành công!").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Lỗi", "Sửa không thành công!").Show();
            return this.FormPanel();
        }
    }
}
